package com.xjscrm.server.service.wwgrouptags.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import com.xjscrm.common.entity.*;
import com.xjscrm.common.enums.RedisCacheKeyEnum;
import com.xjscrm.common.utils.DateUtil;
import com.xjscrm.common.utils.Tools;
import com.xjscrm.common.vo.msg.MsgData;
import com.xjscrm.server.biz.RatelimitService;
import com.xjscrm.server.dto.groupsendjobmsg.GroupSendJobMsgQuery;
import com.xjscrm.server.dto.wwgroup.WwGroupQuery;
import com.xjscrm.server.mapper.WwGroupMapper;
import com.xjscrm.server.mapper.WwGroupTagsRelationMapper;
import com.xjscrm.server.service.wwgrouptags.WwGroupTagsService;
import com.xjscrm.server.vo.device.Device;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * 群发任务异步实现类
 *
 * @author makejava
 * @since 2024-03-01 17:01:12
 */
@Slf4j
@Service
public class WwGroupTagsServiceImpl implements WwGroupTagsService {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private RatelimitService ratelimitService;
    @Autowired
    private WwGroupTagsRelationMapper wwGroupTagsRelationMapper;
    @Autowired
    private WwGroupMapper wwGroupMapper;

    /**
     * 添加群标签
     *
     * @param wwGroupTags
     * @return null
     * @author jitwxs
     * @date 2024/3/8 17:12
     */
    @Async("taskExecutorForXxJob")
    public void addWwGroupTags(WwGroupTags wwGroupTags) {

        try {

            int now = DateUtil.getTime();

            if(wwGroupTags == null){
                return;
            }

            WwGroupQuery wwGroupQuery = new WwGroupQuery();
            wwGroupQuery.setMerId(wwGroupTags.getMerId());
            Page<WwGroup> page = new Page<>();
            page.setCurrent(1);//只查第一页
            page.setSize(10); //每页查询10个
            page.addOrder(OrderItem.asc("id"));//默认id升序
            Long idStart = 0L;
            List<WwGroup> wwGroupList = wwGroupMapper.findByList(page, wwGroupQuery);
            while (wwGroupList != null && wwGroupList.size() > 0) {
                for (WwGroup wwGroup : wwGroupList) {
                    if (wwGroup.getId().longValue() >idStart.longValue()) {
                        idStart = wwGroup.getId();
                    }

                    //限流判断
                    String rateLimitKey = "addWwGroupTags-wwGroupTagsId=" + wwGroupTags.getId() + "-wwGroupId=" + wwGroup.getId();
                    boolean inRateLimit = ratelimitService.inRateLimit(rateLimitKey, 1, 300);
                    if (!inRateLimit) {
                        //logger.info("--inRateLimit false. tradeno={}",alipayDetail.getTradeno());
                        continue;
                    }

                    try {

                        //验证通过，自动打标签
                        boolean result = verifyPara(wwGroupTags, wwGroup);
                        if(result){
                            //判断此标签是否存在
                            WwGroupTagsRelation wwGroupTagsRelation = wwGroupTagsRelationMapper.selectByTagIdAndDeviceIdAndGroupWxid(wwGroupTags.getId(), wwGroup.getDeviceId(), wwGroup.getGroupWxid());
                            if(wwGroupTagsRelation == null){
                                wwGroupTagsRelation = new WwGroupTagsRelation();
                                wwGroupTagsRelation.setId(IdWorker.getId());
                                wwGroupTagsRelation.setMerId(wwGroupTags.getMerId());
                                wwGroupTagsRelation.setTagId(wwGroupTags.getId());
                                wwGroupTagsRelation.setDeviceId(wwGroup.getDeviceId());
                                wwGroupTagsRelation.setGroupWxid(wwGroup.getGroupWxid());
                                wwGroupTagsRelation.setCreateTime(now);
                                wwGroupTagsRelation.setUpdateTime(now);
                                wwGroupTagsRelationMapper.insert(wwGroupTagsRelation);
                            }
                        }
                    } catch (Exception e) {
                        log.error("--封装群发消息失败--error={}", e.getMessage(), e);
                    }finally {
                        //保存成功之后，手动删除限流redisKey
                        redisTemplate.delete(rateLimitKey);
                    }
                }

                wwGroupQuery.setIdStart(idStart);
                wwGroupList = wwGroupMapper.findByList(page, wwGroupQuery);
            }
        } catch (Exception e) {
            log.info(e.getMessage(),e);
        }
    }



    /**
     * 验证群是否自动打标签条件
     *
     * @param wwGroupTags
     * @param wwGroup
     * @return boolean
     * @author jitwxs
     * @date 2024/4/2 9:36
     */
    public boolean verifyPara(WwGroupTags wwGroupTags, WwGroup wwGroup) {

        if (wwGroupTags == null) {
            return false;
        }

        if(wwGroup == null){
            return false;
        }

        Integer groupKeyWordSwitch = Tools.getInteger(wwGroupTags.getGroupKeyWordSwitch());
        Integer upperLimitSwitch = Tools.getInteger(wwGroupTags.getUpperLimitSwitch());
        if(groupKeyWordSwitch.intValue() != 1 && upperLimitSwitch.intValue() != 1){
            return false;
        }

        //验证触发群名称列表
        boolean groupKeyWordFlag = true;
        if(groupKeyWordSwitch.intValue() == 1){//如果开启，则默认为不通过
            groupKeyWordFlag = false;
            //验证群名
            String groupName = Tools.getStr(wwGroup.getGroupName());
            List<String> groupKewordList =  JSONObject.parseArray(wwGroupTags.getGroupKeword(), String.class);
            if(groupKewordList != null && groupKewordList.size() > 0){
                for (String groupKeword : groupKewordList) {
                    if(groupName.contains(groupKeword)){
                        groupKeyWordFlag = true;
                        break;
                    }
                }
            }
        }

        //验证触发人数
        boolean upperLimitFlag = true;
        if (upperLimitSwitch.intValue() == 1) { //群人数上限开启
            upperLimitFlag = false;
            Integer upperLimit = Tools.getInteger(wwGroupTags.getUpperLimit());
            //在群人数
            String groupMemberCountKey = String.format(RedisCacheKeyEnum.GROUP_MEMBER_COUNT.getKey(), wwGroup.getGroupWxid());
            Integer groupMemberCount =  (Integer)redisTemplate.opsForValue().get(groupMemberCountKey);
            Integer memberTotal = Tools.getInteger(groupMemberCount);
            if(memberTotal.intValue() >= upperLimit.intValue()){
                upperLimitFlag = true;
            }
        }

        return groupKeyWordFlag && upperLimitFlag;
    }


}
